package zipFile;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipFile;

/**
 * https://blog.csdn.net/xueyepiaoling/article/details/6119924
 * https://blog.csdn.net/wmg_fly/article/details/91513934
 */
public class ZipFileUtil {

    static final int BUFFER = 1024;

    private static void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */ 
        if (file.isDirectory()) {  
            compressDirectory(file, out, basedir);
        } else {  
            compressFile(file, out, basedir);
        }  
    }

    /** 压缩一个目录 */
    private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {

        if (!dir.exists()) {
            return;
        }

        // 加入文件夹
        try {
            ZipEntry entry = new ZipEntry(basedir + dir.getName() + File.separator);
            out.putNextEntry(entry);
            out.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 加入文件夹内的文件
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + File.separator);
        }
    }

    /** 压缩一个文件 */
    private static void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                                 new FileInputStream(file));
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
            out.closeEntry();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
    * 压缩文件
    * @param srcPath
    */
    public static void compress(String srcPath, String dstFilePath) throws ZipException {
        File file = new File(srcPath);
        if (!file.exists()) {
            throw new ZipException(100, "要压缩的文件目录不存在");
        }
        try {

            OutputStream os = new FileOutputStream(dstFilePath);
            BufferedOutputStream bs = new BufferedOutputStream(os);
            ZipOutputStream out = new ZipOutputStream(bs);

            // Complete File
            String basedir = "";
            compress(file, out, basedir);

            out.close();
            // System.out.println("压缩完成.");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解压
     * @param srcFile 压缩文件
     * @param destDirPath 解压目录
     * @throws RuntimeException
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {

        long start = System.currentTimeMillis();

        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        java.util.zip.ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                java.util.zip.ZipEntry entry = (java.util.zip.ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
//                    byte[] buf = new byte[BUFFER_SIZE];
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }

            }
            long end = System.currentTimeMillis();
            System.out.println("解压完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            // 压缩
            compress("F:\\文件夹", "F:\\压缩包.zip");
            // 解压
            File zipFile = new File("E:\\Desktop\\a.zip");
            unZip(zipFile, "E:\\Desktop\\wwj");
        } catch (ZipException e) {
            System.out.println("错误代码："+e.getErrCode()+"，错误内容："+e.getMessage());
        }
    }

}
